#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
数据库驱动模块
"""
import pymysql
from pymongo import MongoClient
from utils import help
import settings
import datetime


class MongoDB(object):
    def __init__(self, mongo_conf, table_set='word'):
        self.conn = MongoClient(mongo_conf["host"], mongo_conf["port"])
        self.db = self.conn[mongo_conf["db"]]
        self.table_set = self.db[table_set]

    def insert(self, dict_msg):
        """
        插入数据
        :param dict_msg:
        :return:
        """
        try:
            result = self.table_set.insert(dict_msg)
            return result
        except Exception as e:
            print "ERROR:", e

    def query_all(self):
        """
        查找所有数据
        :return:
        """
        try:
            result = self.table_set.find()
            return result
        except Exception as e:
            print "ERROR:", e

    def query_all_data_by_date(self, from_date=None, to_date=None, date_nums=40):
        """
        得到某一段时间的所有数据
        :param from_date: 如:'2017-02-02 00:00:00'
        :param to_date: 如:'2017-02-03 00:00:00'
        :param date_nums: 多少天
        :return: 返回的数据集
        """
        result = []
        if from_date is None and to_date is None:
            print "both from_date and to_date are None..."
            return None
        if to_date is None:
            print "to_date can not be none.."
            return None
        if from_date is None:
            # 按照时间差去寻找
            from_date = help.get_before_date_by_delta(to_date, date_nums)
        if from_date > to_date:
            print 'from_date can not bigger than to_date'
            return None
        # print "正在获取 %s 到 %s时间段的数据,相隔 %d 天..." % (from_date, to_date, date_nums)

        from_date = help.change_str_2_datetime(from_date)
        to_date = help.change_str_2_datetime(to_date)
        # 找出这个时间段的所有数据
        for item in self.table_set.find({"pub_time": {"$gte": from_date, "$lte": to_date}}):
            result.append(item)
        return result

    def query_all_words_by_date(self, from_date=None, to_date=None, date_nums=40):
        """
        查询某个时间段的所有单词数，当做列名
        :param from_date: 开始日期,默认为空
        :param to_date: 结束日期,默认为空
        :param date_nums: 默认天数,默认为40
        :return: result,为该时间段的所有的单词集合
        """
        result = dict()
        if from_date is None and to_date is None:
            print "both from_date and to_date are None..."
            return None
        if to_date is None:
            print "to_date can not be none.."
            return None
        # 转换成时间戳
        to_date_timestap = help.change_datetime_2_timestap(to_date)
        if from_date is None:
            # 按照时间差去寻找
            # from_date_timestap = help.change_datetime_2_timestap(from_date)
            pass
        else:
            from_date_timestap = help.change_datetime_2_timestap(from_date)
        pass


if __name__ == "__main__":
    demo = MongoDB(settings.mongo_db_config)
    to_date = '2017-02-03 00:00:00'
    demo.query_all_data_by_date(from_date='2017-02-02 00:00:00', to_date=to_date)


class DBSession(object):
    def __init__(self, dbconf, cursor=pymysql.cursors.DictCursor):
        self.__conf = dbconf
        self.__cursor = cursor
        try:
            self.__conn = pymysql.connect(host=self.__conf['host'],
                                          port=self.__conf['port'],
                                          user=self.__conf['user'],
                                          password=self.__conf['password'],
                                          charset='utf8',
                                          db=self.__conf['db'],
                                          cursorclass=self.__cursor)
        except Exception, e:
            raise e

    def close(self):
        self.__conn.close()

    def re_connect(self):
        self.__conn = pymysql.connect(host=self.__conf['host'],
                                      port=self.__conf['port'],
                                      user=self.__conf['user'],
                                      password=self.__conf['password'],
                                      charset='utf8',
                                      db=self.__conf['db_name'],
                                      cursorclass=self.__cursor)

    # 执行插入语句
    def execute_insert(self, dml):
        try:
            with self.__conn.cursor() as cursor:
                cursor.execute(dml)
            self.__conn.commit()
        except pymysql.OperationalError as e:
            self.re_connect()
            with self.__conn.cursor() as cursor:
                cursor.execute(dml)
            self.__conn.commit()
        except Exception as e:
            raise e
        return 0

    # 执行查询语句
    def execute_query(self, dml, args=None):
        try:
            with self.__conn.cursor() as cursor:
                cursor.execute(dml, args)
                rs = cursor.fetchall()
            self.__conn.commit()
        except pymysql.OperationalError as e:
            self.re_connect()
            with self.__conn.cursor() as cursor:
                cursor.execute(dml, args)
                rs = cursor.fetchall()
            self.__conn.commit()
        except Exception as e:
            raise e
        return rs

    # 执行批量插入数据语句
    def execute_inset_many(self, dml, args):
        try:
            with self.__conn.cursor() as cursor:
                cursor.executemany(dml, args)
            self.__conn.commit()
        except pymysql.OperationalError as e:
            self.re_connect()
            with self.__conn.cursor() as cursor:
                cursor.executemany(dml, args)
            self.__conn.commit()
        except Exception as e:
            raise e
        return 0

    # 展示数据表
    def show_tb(self):
        with self.__conn.cursor() as cursor:
            cursor.execute('show tables')
            tables = cursor.fetchall()
            tables = [item.values()[0] for item in tables]
        return tables

    def insertmany(self, dml):
        try:
            with self.__conn.cursor() as cursor:
                cursor.executemany(dml)
            self.__conn.commit()
        except Exception, e:
            raise e
        return 0
